/** 业务逻辑 */
import { getCustomerById } from "@/api/customer";
import { getAndroidId, getDeviceSerialNumber } from "@/utils/util";
import { getBusinessPayConfigPage, getBusinessDetailById } from "@/api/user/business";
const business = {
  namespaced: true,
  state: {
    /**
     * 业务逻辑命名方法：  字段名: uni.getStorageSync('__APP__字段名')
     */
    customerInfo: uni.getStorageSync("__APP__customerInfo") || {}, // 客户信息
    businessInfo: uni.getStorageSync("__APP__businessInfo") || {}, // 商家信息
    // 当前消费模式 （设置-模式切换, 对应value 数据）
    consumptionPattern: uni.getStorageSync("__APP__consumptionPattern") || 0,
    // 设备ID
    deviceId: uni.getStorageSync("DEVICE_ID") || "",
    // 商户支付标识
    payCode: import.meta.env.VITE_PAY_CODE,
    // 消费机功能设置
    appSetting: uni.getStorageSync("__APP__appSetting") || {
      // 菜品列表无图模式
      noImageMode: true,
    },
  },
  actions: {
    // 更新客户信息
    async updateCustomerInfo({ commit, state }, paylod = {}) {
      try {
        const id = paylod?.id || state.customerInfo.userId;
        if (!id) console.error("updateCustomerInfo 用户ID不能为空");
        const { data } = await getCustomerById(id);
        if (data) {
          commit("setCustomerInfo", data);
        }
      } catch (error) {
        console.error(error);
      }
    },
    // 更新商家信息
    async updateBusinessInfo({ commit, state }, paylod = {}) {
      // 获取当前用户的商家信息
      try {
        const { data, success } = await getBusinessDetailById();
        if (!success) throw new Error("获取商家信息失败");
        // 存储商家信息
        commit("setBusinessInfo", data);
        /**
         * 获取支付配置
         * - (!) 测试环境下， 支付标识由 平台->支付应用配置->支付标识 决定, 正式环境则固定为 VITE_PAY_CODE
         */
        if (import.meta.env.VITE_KINGON_CUSTOMER_ID == "TestInner181") {
          try {
            // TODO 这里并不是标准用法，只是临时方案
            const pam = {
              appName: data.businessName,
            };
            const { data: payConfigData, success: payConfigSuccess } = await getBusinessPayConfigPage(pam);
            if (payConfigSuccess && payConfigData.records.length == 1) {
              commit("setPayCode", payConfigData.records[0].payCode);
            }
          } catch (error) {
            console.error("获取支付配置失败", error);
          }
        }
      } catch (error) {
        console.error(error);
      }
    },
  },
  mutations: {
    /** 客户信息 */
    setCustomerInfo(state, data) {
      state.customerInfo = data;
      uni.setStorageSync("__APP__customerInfo", data);
    },
    /** 商家信息 */
    setBusinessInfo(state, data) {
      state.businessInfo = data;
      uni.setStorageSync("__APP__businessInfo", data);
    },
    /** 支付配置 */
    setPayCode(state, data) {
      if (!data) return console.warn("支付配置不能为空");
      state.payCode = data;
    },
    /** 设置当前消费模式 */
    setConsumptionPattern(state: any, { mode, relaunch = false }: { mode: number; relaunch?: boolean }) {
      state.consumptionPattern = mode;
      uni.setStorageSync("__APP__consumptionPattern", mode);
      if (relaunch) {
        uni.showLoading({ title: "切换中...", mask: true });
        const timer = setTimeout(() => {
          uni.hideLoading();
          clearTimeout(timer);
          // 重新加载
          uni.reLaunch({ url: import.meta.env.VITE_PAGE_HOME });
        }, 1000);
      }
    },
    async initDeviceId(state) {
      // 获取ANDROIDid
      const did = await getDeviceSerialNumber();
      state.deviceId = did;
      uni.setStorageSync("DEVICE_ID", did);
      return did;
    },
    /** 消费机功能设置 （单个） */
    setAppSettingByKey(state, { key, value }) {
      state.appSetting[key] = value;
      uni.setStorageSync("__APP__appSetting", state.appSetting);
    },
    /** 消费机功能设置 （全部） */
    setAppSetting(state, data) {
      state.appSetting = data;
      uni.setStorageSync("__APP__appSetting", data);
    },
    onLogout(state) {
      // 退出登陆时，会调用该方法，需要再此处理相关业务数据的，在这写；默认会清除所有业务数据
      console.log("business onLogout");
      const clearKeys = Object.keys(state);
      clearKeys.forEach((key) => {
        const keyName = "__APP__" + key;
        state[keyName] = {};
        uni.removeStorageSync(keyName);
      });
    },
    clear(state: any) {
      // 清除数据
      const clearKeys = Object.keys(state);
      clearKeys.forEach((key) => {
        const keyName = "__APP__" + key;
        state[keyName] = {};
        uni.removeStorageSync(keyName);
      });
    }
  },
  getters: {
    consumptionPattern: (state) => state.business.consumptionPattern,
    businessInfo: (state) => state.business.businessInfo,
    localFaceData: (state) => state.business.localFaceData,
    localFaceDataLastUpdateTime: (state) => state.business.localFaceDatalastUpdateTime || "未更新",
    deviceId: (state) => state.business.deviceId,
    payCode: (state) => state.business.payCode,
    appSetting: (state) => state.business.appSetting,
  },
};
export default business;
